package org.simple.controller;

import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.simple.util.AjaxResult;
import org.simple.util.FastDfsApiOpr;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;


import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.IOException;

@RestController
@RequestMapping("/fastDfs")
public class FastDfsController {
    //crud 上传 下载（查看） 删除 修改（先删除后添加）



/**
 * 参数：上传文件
 * 返回值：成功与否，还要返回地址
 */

@PostMapping(produces = {MediaType.APPLICATION_JSON_UTF8_VALUE}
        , consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public AjaxResult upload(@RequestPart(required = true,value = "file")MultipartFile file){
    try {
        System.out.println(file.getOriginalFilename() + ":" + file.getSize());
        String originalFilename = file.getOriginalFilename();
        // xxx.jpg
        String extName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
        System.out.println(extName);
        String filePath =  FastDfsApiOpr.upload(file.getBytes(), extName);
        return AjaxResult.me().setResultObj(filePath); //把上传后的路径返回回去
    } catch (IOException e) {
        e.printStackTrace();
        return AjaxResult.me().setSuccess(false).setMessage("上传失败!"+e.getMessage());
    }
}


    //下载
    @GetMapping
    void download(@RequestParam(required = true,value = "path") String path, HttpServletResponse response){
        ByteArrayInputStream bis = null;
        ServletOutputStream outputStream = null;
        try{
            String pathTmp = path.substring(1); // goup1/xxxxx/yyyy
            String groupName =  pathTmp.substring(0, pathTmp.indexOf("/")); //goup1
            String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);// xxxxx/yyyy
            System.out.println(groupName);
            System.out.println(remotePath);
            byte[] data = FastDfsApiOpr.download(groupName, remotePath);

            //以流方式直接做响应 不需要返回Response
            bis = new ByteArrayInputStream(data);
            outputStream = response.getOutputStream();
            IOUtils.copy(bis,outputStream);
        }catch (Exception e
                ){
            e.printStackTrace();
        }
        finally {
           /* if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }   */
        }
    }


 /*   @PostMapping
    public AjaxResult upload(@RequestParam(required = true,value = "file")MultipartFile file){
        try {
            System.out.println(file.getOriginalFilename() + ":" + file.getSize());
            String originalFilename = file.getOriginalFilename();
            // xxx.jpg
            String extName = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
            System.out.println(extName);
            String filePath =  FastDfsApiOpr.upload(file.getBytes(), extName);
            return AjaxResult.me().setResultObj(filePath); //把上传后的路径返回回去
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("上传失败!"+e.getMessage());
        }
    }*/




/**
 * 参数：完整路径 /goup1/xxxxx/yyyy
 * 返回值：成功与否，还要返回地址
 *
 */

    @DeleteMapping
    public AjaxResult del(@RequestParam(required = true,value = "path") String path){
        String pathTmp = path.substring(1);
        String groupName =  pathTmp.substring(0, pathTmp.indexOf("/"));
        String remotePath = pathTmp.substring(pathTmp.indexOf("/")+1);
        System.out.println(groupName);
        System.out.println(remotePath);
        FastDfsApiOpr.delete(groupName, remotePath);
        return  AjaxResult.me();
    }
}

